import { catchAwait, cloneDeep, defer, Request } from "utils-lib-js";
import {
  FileItem,
  getDefaultHeaders,
  getDefaultParams,
  PageParams,
  ResultData,
  saveFile,
} from "./utils";

const request = new Request("https://drive-h.quark.cn");
const blackList = ["公众号”阿宇宝库“，获取更多免费资源.txt"];
const pageParams = {
  page: 1,
  pageSize: 500,
  dirId: "8a284fb50f7b440ea5c3ba5483393dad", // 当前文件夹id，通过URL获取
  // pwd_id: "", // 凭证字符
  // stoken: "", // 校验码ID,会过期
  deep: false, // 深度遍历,获取其子文件夹下全部文件，扁平化展示
  showDir: false, // 展示每级文件夹名称
  sort: "file_type:asc,updated_at:desc",
  onlyDir: false, // 只展示文件夹，不展示文件
  maxDir: 3,
  delay: 1 * 0,
};
const fileApi = "/1/clouddrive/file/sort"; // 自己网盘下获取文件夹，要token
// const fileApi = "/1/clouddrive/share/sharepage/detail";// 分享文件下获取文件夹，要pwd_id和stoken

const headers = getDefaultHeaders({
  cookie,
});
let total = 0;
const getAllListData = async (pageParams: PageParams, list = []) => {
  const params = getDefaultParams(pageParams);
  const [err, res] = await catchAwait(
    request.GET(`${fileApi}?${params}`, {}, null, {
      headers,
    })
  );
  await new Promise((resolve) => setTimeout(resolve, pageParams.delay));
  const result: ResultData = res;
  if (err) return console.error("err", err);
  total = result.metadata._total;
  if (!total) return console.log("没有数据");
  if (total > 0 && (pageParams.page - 1) * pageParams.pageSize >= total) {
    console.log(`当前列表${pageParams.dirId}获取完成`);
    return list;
  }
  console.log(`当前在${pageParams.dirId}的第${++pageParams.page}页`);
  list.push(
    ...result.data?.list.filter((it) => !blackList.includes(it.file_name))
  );
  return getAllListData({ ...pageParams }, list);
};
const getSubFolderList = async (pageParams: PageParams) => {
  const source: FileItem[] = [];
  const getSource = async (pageParams: PageParams, upItem?: FileItem) => {
    if (pageParams.maxDir <= 0) return;
    const list = (await getAllListData(cloneDeep(pageParams))) ?? [];
    if (!pageParams.deep && list) return source.push(...list);
    if (list && list?.length) {
      const dirList = list.filter((it) => it.dir);
      const fileList = list.filter((it) => it.file);
      if (dirList?.length) {
        await Promise.all(
          dirList?.map(async (it) => {
            const params = cloneDeep(pageParams);
            params.dirId = it.fid;
            const maxDir = params.maxDir - 1;
            return getSource({ ...params, maxDir }, it);
          })
        );
      }
      const resultList = (pageParams.onlyDir ? dirList : fileList).map((it) =>
        pageParams.showDir
          ? { ...it, file_name: `${upItem?.file_name ?? ""}/${it.file_name}` }
          : it
      );
      source.push(...resultList);
    }
    return list;
  };
  await getSource({ ...pageParams });
  return source;
};
getSubFolderList(pageParams).then((list: any) => {
  console.log("执行完毕", list.length);
  // ${it.fid}*$#
  list &&
    saveFile(
      list?.map((it) => `${it.file_name}`).join("\n"),
      "./list.txt"
    ); // 导出到list文件下
});
